﻿using System;
using System.Security.Principal;
using Csla.Security;
using Csla.Serialization;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Library.BusinessObjects.People;

namespace BizControl.Library.Security
{
  [Serializable()]
  public class BizControlPrincipal : CslaPrincipal
  {
    public PersonBO Person { get; set; }

    ModelBO _model;
    public ModelBO Model 
    {
      get
      {
        return _model;
      }
      set
      {
        if (value != _model)
          _model = value;
        //Person.IsLogin = false;
        if (_model != null)
          Person = PersonBO.GetPerson(Person.PersonId);
      }
    }

    private BizControlPrincipal(IIdentity identity, PersonBO person) 
      : base(identity)
    {
      Person = person;
    }

    public static bool Login(string username, string password)
    {
      return SetPrincipal(BizControlIdentity.GetIdentity(username, password));
    }

    public static void LoadPrincipal(string username)
    {
      SetPrincipal(BizControlIdentity.GetIdentity(username));
    }

    private static bool SetPrincipal(BizControlIdentity identity)
    {
      if (identity.IsAuthenticated)
      {
        BizControlPrincipal principal = new BizControlPrincipal(identity, identity.Person);
        Csla.ApplicationContext.User = principal;
      }
      return identity.IsAuthenticated;
    }

    public static void Logout()
    {
      var currentUser = Csla.ApplicationContext.User as BizControlPrincipal;
      if (currentUser != null)
        currentUser.Person = null; // cleaning
      Csla.ApplicationContext.User = new UnauthenticatedPrincipal();
    }
  }
}
